<?php

class Sistema_MenuController extends App_Controller_Action {
    
    private $_file_col  = 'MEN_FILE'; 
    public $dir = 'public/upload/menu/';
    //public  $db = '';
     
    public function init()
    {   
        //$this->db = Zend_Db_Table_Abstract::getDefaultAdapter();
        /* Initialize action controller here */
    }

    public function indexAction() {
        $obj = new Sistema_Model_DbTable_Menu();
        $result = $obj->fetchAll($obj->select()->order('MEN_ORD ASC'));
        $this->view->result = $this->paginacao($result);
    }
    
    public function editAction() {
        $form = new Sistema_Form_Menu();
        
        Zend_Loader::loadClass('imagem','library');
        
        $this->view->form = $form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
                $id = (int) $form->getValue('MEN_ID');
                
                $returnImg = imagem::upload($this->_file_col,$this->dir,$id);
                
                $data = array(
                    'MEN_NOME' => $form->getValue('MEN_NOME'),
                    'MEN_ORD' => $form->getValue('MEN_ORD'),
                    'MEN_CSS' => $form->getValue('MEN_CSS'),
                );
                $obj = new Sistema_Model_DbTable_Menu();

                if ($id == 0){
                    $obj->insert($data);
                    $id =  $obj->getAdapter()->lastInsertId();                    
                    imagem::rename($id,$this->dir,$returnImg['filenew']);
                }
                else
                    $obj->update($data, 'MEN_ID = ' . $id);
                
                if(strlen($_FILES[$this->_file_col]['tmp_name']) > 1){
                    $img = glob($this->dir.$id.'.*');
                    foreach($img as $filetemp) $filename = $filetemp;
                    imagem::reizeFull($filename,$filename, '27', '20');
                }
                
                $this->_helper->redirector('index');
            } else {
                $form->populate($formData);
            }
        } else {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $obj = new Sistema_Model_DbTable_Menu();
                $form->populate($obj->fetchRow('MEN_ID = ' . $id)->toArray());
            }
        }
    }

    public function deleteAction() {
        $id = $this->_getParam('id', 0);
        if ((int)$id > 0 ) {
            $obj = new Sistema_Model_DbTable_Menu();
            $obj->delete('MEN_ID = '.(int)$id);
            $this->_helper->redirector('index');
        } else {
            $id = $this->_getParam('id', 0);
            $obj = new Sistema_Model_DbTable_Menu();
            $form->populate($obj->fetchRow('MEN_ID = ' . $id)->toArray());
        }
    }

}

